package com.why.cachecloud.web.util;

import com.why.cachecloud.configuration.constant.AppCheckEnum;
import com.why.cachecloud.configuration.constant.RedisConfigTemplateChangeEnum;
import com.why.cachecloud.service.custom.alert.DingTalkComponent;
import com.why.cachecloud.entity.AppAudit;
import com.why.cachecloud.entity.AppDesc;
import com.why.cachecloud.entity.AppUser;
import com.why.cachecloud.entity.InstanceConfig;
import com.why.cachecloud.service.stats.app.AppStatsCenter;
import com.why.cachecloud.util.ConstUtils;
import com.why.cachecloud.web.enums.SuccessEnum;
import com.why.cachecloud.web.service.UserService;
import com.why.cachecloud.web.vo.AppDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * 邮件通知应用的申请流程(方法内是具体的文案)
 *
 * @Author why
 */
@Component
@Slf4j
public class AppDingTalkUtil {
    private final Logger logger = LoggerFactory.getLogger(AppDingTalkUtil.class);

    @Autowired
    private DingTalkComponent dingTalkComponent;

    @Autowired
    private UserService userService;

    @Autowired
    private AppStatsCenter appStatsCenter;

    /**
     * 应用状态通知
     *
     * @param appDesc
     * @param appAudit
     */
    public void noticeAppResult(AppDesc appDesc, AppAudit appAudit) {
        appDesc.setOfficer(userService.getOfficerName(appDesc.getOfficer()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder();
        sb.append("#### 应用状态通知 ");
        // 0:等待审批; 1:审批通过; -1:驳回
        if (appAudit.getStatus() == 0) {
            sb.append(ConstUtils.getPhoneString()).append(" \n\n");
        } else {
            List<AppUser> appUsers = userService.getByAppId(appAudit.getAppId());
            List<String> mobileList = appUsers.stream().map(AppUser::getMobile).collect(Collectors.toList());
            sb.append(ConstUtils.getPhoneString(mobileList)).append(" \n\n");
        }
        sb.append("- 申请处理信息：\n\n")
                .append("申请类型：").append(appAudit.getTypeDesc()).append("\n\n")
                .append("申请描述：").append(appAudit.getInfo()).append("\n\n")
                .append("申请时间：").append(appAudit.getCreateTimeFormat()).append("\n\n")
                .append("处理状态：").append(appAudit.getStatusDesc()).append("\n\n")
                .append("处理描述：").append(StringUtils.isBlank(appAudit.getRefuseReason()) ? "" : appAudit.getRefuseReason()).append("\n\n")
                .append("处理时间：").append(simpleDateFormat.format(appAudit.getModifyTime())).append("\n\n")
                .append("- 应用详细信息：\n\n")
                .append("应用名称：").append(appDesc.getName()).append("\n\n")
                .append("应用类型：").append(appDesc.getTypeDesc()).append("\n\n")
                .append("应用状态：").append(appDesc.getStatusDesc()).append("\n\n")
                .append("是否测试：").append(appDesc.getIsTest() == 1 ? "是" : "否").append("\n\n")
                .append("是否持久化：").append(appDesc.getNeedPersistence() == 1 ? "是" : "否").append("\n\n")
                .append("应用描述：").append(appDesc.getIntro()).append("\n\n").append("应用负责人：")
                .append(appDesc.getOfficer()).append("\n\n").append("应用申请时间：")
                .append(simpleDateFormat.format(appDesc.getCreateTime())).append("\n\n");
        dingTalkComponent.sendDingTalkToAdmin(sb.toString());
    }

    /**
     * API应用状态通知
     *
     * @param appDesc
     * @param appAudit
     */
    public void noticeAppResultByApi(AppDesc appDesc, AppAudit appAudit) {
        appDesc.setOfficer(userService.getOfficerName(appDesc.getOfficer()));
        AppUser appUser = userService.get(appDesc.getUserId());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder();
        sb.append("#### API应用申请通知 @").append(appUser.getMobile()).append(" \n\n")
                .append("- 申请处理信息：\n\n")
                .append("申请类型：").append(appAudit.getTypeDesc()).append("\n\n")
                .append("申请描述：").append(appAudit.getInfo()).append("\n\n")
                .append("申请时间：").append(appAudit.getCreateTimeFormat()).append("\n\n")
                .append("处理状态：").append(appAudit.getStatusDesc()).append("\n\n")
                .append("处理描述：").append(StringUtils.isBlank(appAudit.getRefuseReason()) ? "" : appAudit.getRefuseReason()).append("\n\n")
                .append("处理时间：").append(simpleDateFormat.format(appAudit.getModifyTime())).append("\n\n")
                .append("- 应用详细信息：\n\n")
                .append("应用名称：").append(appDesc.getName()).append("\n\n")
                .append("应用类型：").append(appDesc.getTypeDesc()).append("\n\n")
                .append("应用状态：").append(appDesc.getStatusDesc()).append("\n\n")
                .append("是否测试：").append(appDesc.getIsTest() == 1 ? "是" : "否").append("\n\n")
                .append("是否持久化：").append(appDesc.getNeedPersistence() == 1 ? "是" : "否").append("\n\n")
                .append("应用描述：").append(appDesc.getIntro()).append("\n\n")
                .append("应用负责人：").append(appDesc.getOfficer()).append("\n\n")
                .append("应用申请时间：").append(simpleDateFormat.format(appDesc.getCreateTime())).append("\n\n");
        ArrayList<String> phoneList = new ArrayList<>();
        phoneList.add(appUser.getMobile());
        dingTalkComponent.sendDingTalk(sb.toString(), phoneList);
    }

//    /**
//     * 重要应用抄送
//     *
//     * @param appDesc
//     * @param appAudit
//     * @return
//     */
//    private List<String> getCCEmailList(AppDesc appDesc, AppAudit appAudit) {
//        Set<String> ccEmailSet = new LinkedHashSet<>();
//        for (String email : emailComponent.getAdminEmail().split(ConstUtils.COMMA)) {
//            ccEmailSet.add(email);
//        }
//        //S级别，且是开通邮件
//        if (appDesc.isSuperImportant() && AppAuditType.APP_AUDIT.getValue() == appAudit.getType()) {
//            ccEmailSet.addAll(ConstUtils.LEADER_EMAIL_LIST);
//        }
//        return new ArrayList<>(ccEmailSet);
//    }

    /**
     * 注册用户通知
     *
     * @param appUser
     * @param appAudit
     */
    public void noticeUserResult(AppUser appUser, AppAudit appAudit, String typeName) {
        if (appAudit == null) {
            return;
        }
        StringBuilder mailContent = new StringBuilder();
        if (AppCheckEnum.APP_WATING_CHECK.value().equals(appAudit.getStatus())) {
            mailContent.append("#### 注册用户通知 ").append(ConstUtils.getPhoneString()).append(" \n\n");
            mailContent.append(appUser.getChName()).append("申请成为CacheCloud").append(typeName).append("，请管理员处理！");
            dingTalkComponent.sendDingTalkToAdmin(mailContent.toString());
        } else if (AppCheckEnum.APP_PASS.value().equals(appAudit.getStatus())) {
            mailContent.append("#### 注册用户通知 @").append(appUser.getMobile()).append(" \n\n");
            mailContent.append("您的用户申请已经审批通过，您可以正常登录Cachecloud了！");
            dingTalkComponent.sendDingTalk(mailContent.toString(), Collections.singletonList(appUser.getMobile()));
        } else if (AppCheckEnum.APP_REJECT.value().equals(appAudit.getStatus())) {
            mailContent.append("#### 注册用户通知 @").append(appUser.getMobile()).append(" \n\n");
            mailContent.append("您的用户申请被驳回，原因是: ").append(appAudit.getRefuseReason());
            dingTalkComponent.sendDingTalk(mailContent.toString(), Collections.singletonList(appUser.getMobile()));
        }
    }

    /**
     * 应用下线通知
     *
     * @param appUser
     * @param appId
     * @param isSuccess
     */
    public void noticeOfflineApp(AppUser appUser, Long appId, boolean isSuccess) {
        AppDetailVO appDetailVO = appStatsCenter.getAppDetail(appId);
        List<String> mobileList = appDetailVO.getMobileList();
        String mailContent = "#### 应用下线通知 " + ConstUtils.getPhoneString(mobileList) + " \n\n" +
                appUser.getChName() + ",对应用appid=" + appId +
                "进行下线,操作结果是" + (isSuccess ? "下线任务执行成功" : "下线任务失败,请关注任务流日志,请知晓!");
        dingTalkComponent.sendDingTalkToAll(mailContent, mobileList);
    }

    public void sendRedisConfigTemplateChangeEmail(AppUser appUser, String versionName, InstanceConfig instanceConfig,
                                                   SuccessEnum successEnum, RedisConfigTemplateChangeEnum redisConfigTemplateChangeEnum) {
        String mailContent = String.format("#### Redis配置模板修改通知 " + ConstUtils.getPhoneString() + " \n\n %s 对 %s 配置模板 进行了%s,操作结果是%s,具体为(key=%s,value=%s,状态为%s)",
                appUser.getChName(), versionName,
                redisConfigTemplateChangeEnum.getInfo(), successEnum.info(), instanceConfig.getConfigKey(),
                instanceConfig.getConfigValue(), instanceConfig.getStatusDesc());
        dingTalkComponent.sendDingTalkToAdmin(mailContent);
    }

//    public void sendAddRedisVersionEmail(AppUser appUser, String versionName, SuccessEnum successEnum) {
//        String mailTitle = "【CacheCloud】- 新增Redis版本通知";
//        String mailContent = String.format("%s 新增Redis版本:%s ,状态为:%s)", appUser.getChName(), versionName, successEnum.info());
////        emailComponent.sendMail(mailTitle, mailContent.toString(), Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA)));
//    }

    public void sendSystemConfigDifEmail(AppUser appUser, Map<String, String> systemDifConfigMap,
                                         SuccessEnum successEnum) {
        if (MapUtils.isEmpty(systemDifConfigMap)) {
            return;
        }
        StringBuilder mailContent = new StringBuilder();
        mailContent.append("#### 系统配置修改通知 ").append(ConstUtils.getPhoneString()).append(" \n\n").append(appUser.getChName()).append("修改了系统配置，修改结果:").append(successEnum.info()).append(" \n\n");
        mailContent.append("具体配置如下：\n\n");
        mailContent.append("--- \n\n");
        for (Entry<String, String> entry : systemDifConfigMap.entrySet()) {
            mailContent.append(entry.getKey()).append("-->").append(entry.getValue()).append(" \n\n");
        }
        dingTalkComponent.sendDingTalkToAdmin(mailContent.toString());
    }

    /**
     * 系统通知
     *
     * @param noticeContent
     * @return
     */
    public boolean noticeAllUser(String noticeContent) {
        if (StringUtils.isBlank(noticeContent)) {
            return false;
        }
        try {
            List<String> mobileList = new ArrayList<>();
            List<AppUser> appUserList = userService.getUserList(null);
            if (CollectionUtils.isEmpty(appUserList)) {
                return false;
            }
            for (AppUser appUser : appUserList) {
                String mobile = appUser.getMobile();
                if (StringUtils.isBlank(mobile)) {
                    continue;
                }
                if (!mobileList.contains(mobile)) {
                    mobileList.add(mobile);
                }
            }

            StringBuilder mailContent = new StringBuilder();
            mailContent.append("#### 系统通知 ").append(ConstUtils.getPhoneString(mobileList)).append(" \n\n");
            String[] noticeArray = noticeContent.split(ConstUtils.NEXT_LINE);
            for (String noticeLine : noticeArray) {
                mailContent.append(noticeLine).append(" \n\n");
            }

            dingTalkComponent.sendDingTalkToAll(mailContent.toString(), mobileList);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return false;
    }

}
